package com.hnluchuan.bmjlearning.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhoutianyang on 18-5-7.
 * @author zhoutianyang
 */
public class CustomDateUtil {
    public static final String DATEFORMAT_YMD = "yyyy-MM-dd";


    public static final SimpleDateFormat shortSdf
            = new SimpleDateFormat(DATEFORMAT_YMD);
    private static final Pattern TIME_P = Pattern.compile("(\\d+)时(\\d+)分(\\d+)秒(\\d+)毫秒");
    public static SimpleDateFormat dmy_hm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    static String[] parsePatterns = { "yyyy-MM-dd", "yyyy/MM/dd" };
    private static Log log = LogFactory.getLog(CustomDateUtil.class);

    public static String formatDateYMDToStr(Date date) {
        if (date == null)
            return null;
        try {
            return dmy_hm.format(date);
        } catch (Exception e) {
            log.debug("DateUtil.formatDateYMDToStr():" + e.getMessage());
            return null;
        }

    }

    /*
     * 得到当前日期字符串 格式（yyyy-MM-dd）
     */
    public static String getDate() {
        return DateFormatUtils.format(new Date(), "yyyy-MM-dd");
    }

    /*
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (null == date)
            return formatDate;

        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    /*
     * 得到当前时间字符串 格式（HH:mm:ss）
     */
    public static String getTime() {
        return (new DateTime()).toString("HH:mm:ss");
    }

    /*
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return (new DateTime()).toString("yyyy-MM-dd HH:mm:ss");
    }

    public static String getDateTimeMill() {
        return (new DateTime()).toString("yyMMddHHmmssSSS");
    }

    /*
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek() {
        return (new DateTime()).toString("E");
    }

    /*
     * 天数相加
     */
    public static Date addDay(Date date, int d) {
        return org.apache.commons.lang3.time.DateUtils.addDays(date, d);
    }

    /*
     * 日期型字符串转化为日期 格式（"yyyy-MM-dd","yyyy/MM/dd"）
     */
    public static Date parseDate(String str, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.parse(str);
    }

    /**
     * 获取日期在一年当中是的第几天
     * @param date
     * @return
     */
    public static int daysOfDate(Date date) {
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(date);
        return aCalendar.get(Calendar.DAY_OF_YEAR);
    }

    /**
     *
     * @Title: toMillisecond
     * @Description: 将 xx时xx分xx秒xx毫秒 化成 毫秒
     * @param time
     * @return Long
     */
    public static Long toMillisecond(String time) {
        String orgTime = time;
        if (StringUtils.isEmpty(time))
            return null;
        if (!time.contains("分"))
            time = "0分" + time;
        if (!time.contains("时"))
            time = "0时" + time;
        if (!time.contains("毫秒"))
            time = time + "毫秒";
        Matcher m = TIME_P.matcher(time);
        if (m.matches()) {
            Long l = 0L;
            String h = m.group(1);
            l = l + Long.parseLong(h) * 60 * 60 * 1000;
            String min = m.group(2);
            l = l + Long.parseLong(min) * 60 * 1000;
            String s = m.group(3);
            l = l + Long.parseLong(s) * 1000;
            String ms = m.group(4);
            l = l + Long.parseLong(ms);
            return l;
        } else {
            throw new IllegalArgumentException("无效的时间格式：" + orgTime);
        }
    }

    public static Timestamp getTimestamp(Date... dates) {
        if (dates == null || dates.length == 0) {
            return new Timestamp(System.currentTimeMillis());
        } else {
            return new Timestamp(dates[0].getTime());
        }
    }

    /**
     * 比较两个日期相差的天数
     *
     */
    public static int getDiffDays(String date1, String date2) {
        int margin;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            ParsePosition pos = new ParsePosition(0);
            ParsePosition pos1 = new ParsePosition(0);
            Date dt1 = sdf.parse(date1, pos);
            Date dt2 = sdf.parse(date2, pos1);
            long l = dt1.getTime() - dt2.getTime();
            margin = (int) (l / (24 * 60 * 60 * 1000));
            return margin;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static int getDiffDays(Date dt1, Date dt2) {
        int margin;
        try {
            long l = dt1.getTime() - dt2.getTime();
            margin = (int) (l / (24 * 60 * 60 * 1000));
            if (margin == 0) {
                margin = dt1.getDay() - dt2.getDay();
            }
            return margin;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static int getDiffYeas(Date dt1, Date dt2) {
        int margin;
        try {
            margin = dt1.getYear() - dt2.getYear();
            return margin;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     *
     * @Title: isAfter
     * @Description: d2 在 d1 后则返回true
     * @param d1
     * @param d2
     * @return boolean
     */
    public static boolean isAfter(Date d1, Date d2) {
        if (d1 != null && d2 != null)
            return d1.before(d2);
        else
            return false;
    }

    public static Date splitDay(Date d) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取某年第一天日期
     *
     * @param year
     *            年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year
     *            年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return currYearLast;
    }

    /**
     * String转换成Date的yyyy-MM-dd格式
     *
     * @param strDate
     * @return
     */
    public static Date getShortTimeDate(String strDate) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        }
        Date date = null;
        try {
            date = shortSdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String favoriteRaces = "aaa,vvv,";
        if (!StringUtils.isEmpty(favoriteRaces)) {
            favoriteRaces = favoriteRaces.substring(0, favoriteRaces.length() - 1);
        }
        System.out.println(favoriteRaces);
    }
}
